import { Version } from '../utils/Version'
import { reactive } from 'vue'
import { UniStore } from '../utils/UniStorege'

export const useVersion = function() {
  const dl = reactive({
    progress:0,
    totalBW:0,
    totalBWE:0
  })
  const getApk = function(url, ver) {
    const downloadTask = uni.downloadFile({
      url: url, //仅为示例，并非真实的资源
      header:{
        Authorization: 'Bearer ' + UniStore.getT()
      },
      timeout:15 * 1000,
      success: (res) => {
        if (res.statusCode === 200) {
          const { tempFilePath } = res
          uni.openDocument({
            filePath: tempFilePath,
            success(res) {
              //更新系统版本号
              Version.setVersionNumber(ver)
              UniStore.setT(null)
              UniStore.removeObject('__u203')
            }
          })
        }
      },
      fail(res) {
        uni.showToast({
          title: '下载失败请稍后再试',
          icon: 'none',
          duration: 1500
        })
      }
    })
    const downloading = (res)=>{
      const {
        progress,
        totalBytesWritten,
        totalBytesExpectedToWrite
      } = res || {}

      dl.progress = progress
      dl.totalBW = totalBytesWritten
      dl.totalBWE = totalBytesExpectedToWrite
    }
    uni.showModal({
      title:'正在下载...',
      showCancel:false,
      confirmText:'取消下载',
      confirmColor:"#000",
      content:`进度: ${dl.progress}% |-> (${dl.totalBW}/${dl.totalBWE})`,
      success({confirm}){
        if(confirm){
          downloadTask.offProgressUpdate(downloading)
          downloadTask.abort()
          console.log("download's been canceled")
        }
      }
    })
    downloadTask.onProgressUpdate(downloading)
  }

  const checkNewVersion = function(res) {
    return new Promise((resolve, reject) => {
      // #ifdef APP
      Version.resetVersionNumber()
      plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
        console.log(wgtinfo)
        const DEFAULT_VERSION = '1.0.12'
        let _v = DEFAULT_VERSION
        let _app_v = DEFAULT_VERSION
        const { version } = wgtinfo
        const localVersion = Version.getVersionNumber()

        if (version) {
          _app_v = version
        } else {
          if (localVersion) {
            _app_v = localVersion
          }
        }

        if (localVersion) {
          _v = localVersion
        } else {
          if (version) {
            _v = version
          }
        }

        console.log('[version update] result', res, '[local v]', _v, version)
        if (res === null) {
          reject()
          return
        }
        const {
          name: servVer,
          description: verDesc,
          apkPath
        } = res
        if (_v === servVer && _v === _app_v) {
          Version.setVersionNumber(servVer)
          reject()
          return
        }
        console.log("cache cleared")
        plus.cache.clear()
        console.log(apkPath)
        uni.showModal({
          title: '新版本提醒',
          content: '版本号:' + servVer + '\n' +
            '当前版本:' + _app_v + '\n' +
            '更新内容:' + verDesc,
          showCancel: true,
          success: (res) => {
            if (res.confirm) {
              getApk(apkPath, servVer) //下载并安装
            } else {
              reject()
            }
          }
        })
      })
      // #endif
      // #ifdef H5
      console.log('you are using H5 mode. version checks will not work!')
      reject()
      // #endif
    })
  }

  return {
    checkNewVersion,
    getApk
  }
}

